#include "StdAfx.h"
#include "DBHelper.h"
#include "CodeTool.h"

CDBHelper::CDBHelper()
{
	m_strAppRoot = CCodeTool::Xqm_GetRoot();
	m_strConnection = _T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+m_strAppRoot+"Diabetes.mdb;Persist Security Info=False;Jet OLEDB:Database Password=1002310023");
	if(m_pDb.Open(m_strConnection))
	{
		m_pRs = CADORecordset(&m_pDb);
	}	
}

CDBHelper::~CDBHelper()
{
	if(m_pRs.IsOpen()){
		m_pRs.Close();
	}
	if(m_pDb.IsOpen()){
		m_pDb.Close();
	}
}

BOOL CDBHelper::IsExist(CString sql)
{
	return ( (m_pRs.Open(sql,CADORecordset::openQuery))&&(m_pRs.GetRecordCount() > 0) );
}
BOOL CDBHelper::ExecuteNonQuery(CString cmdText)
{
	return ( (m_pDb.IsOpen())&&(m_pDb.Execute(cmdText))&&(m_pDb.GetRecordsAffected() >0) );
}
CKeyValue CDBHelper::GetListByKw(CString kw)
{
	CString sql = "SELECT * FROM SearchInfo WHERE Key LIKE '%"+kw+"%'";

	BOOL boolRet = m_pRs.Open(sql,CADORecordset::openQuery);
	int intRet = m_pRs.GetRecordCount();

	CKeyValue list;

	if(!boolRet||(m_pRs.GetRecordCount()<=0))
	{
		list.Clear();
	}
	else
	{
		for(int i=0;i<intRet;i++)
		{
			CString key,val;
			m_pRs.GetFieldValue("key",key);
			m_pRs.GetFieldValue("answer",val);

			string skey = string(key.GetBuffer(key.GetLength()));
			string sval = string(val.GetBuffer(val.GetLength()));

			list.Insert(skey, sval);
			m_pRs.MoveNext();
			if(m_pRs.IsEof())
			{
				break;	
			}
		}
	}
	return list;
}